# Copyright 2018 Tecnativa - Carlos Dauden
# License AGPL-3.0 or later (https://www.gnu.org/licenses/agpl).
from odoo import api, fields, models, _
from odoo.addons import decimal_precision as dp
from odoo.tools.float_utils import float_compare, float_round
import logging
import json
from odoo.tools import float_is_zero
_logger = logging.getLogger(__name__)


class StockQuant(models.Model):
    _inherit = 'stock.quant'

    product_style = fields.Many2one(
        related='product_tmpl_id.categ_id', store=True, string=u"产品类型")


class StockMove(models.Model):
    _inherit = "stock.move"

    eh_location_id = fields.Many2one(
        'stock.location', '仓库',)


class StockPicking(models.Model):
    _inherit = "stock.picking"

    en_is_auto_generate_picking = fields.Boolean(
        string='是否已自动生成', default=False)

    partner_id = fields.Many2one(
        'res.partner', 'Partner',
        states={'done': [('readonly', True)], 'cancel': [('readonly', True)]}, required=True)

    owner_id = fields.Many2one(
        'res.partner', 'Owner',
        states={'done': [('readonly', True)], 'cancel': [('readonly', True)]},
        help="Default Owner", required=True)

    @api.multi
    def button_validate(self):
        action = super(StockPicking, self).button_validate()
        self.action_assign_owner()
        return action

    @api.multi
    def en_generate_picking(self):
        _logger.info('en_generate_picking')
        picking_type_id = self._get_picking_type_id()
        _logger.info('picking_type_id %s ', picking_type_id.id)
        location_ids = self._get_location_arrow()
        _logger.info(location_ids)
        if(self.picking_type_code == 'incoming'):
            self._generate_pickings('incoming', picking_type_id, location_ids)
            # _logger.info(pickings)
            return
        elif(self.picking_type_code == 'outgoing'):
            self._generate_pickings('outgoing', picking_type_id, location_ids)
            return

    def _get_picking_type_id(self):
        picking_type_id = self.env['stock.picking.type'].search(
            [('code', '=', 'internal')])[0]
        return picking_type_id

    def _get_location_arrow(self):
        # return location_ids = {18: [stock.move(26,), stock.move(30,)], 19: [stock.move(27,)]}
        location_ids = {}
        for move in self.move_lines:
            if move.eh_location_id:
                if move.eh_location_id.id not in location_ids:
                    location_ids[move.eh_location_id.id] = []
                location_ids[move.eh_location_id.id].append(move)
        return location_ids

    def _generate_pickings(self, in_out, picking_type_id, dest_location_ids):
        # arg  dest_location_ids = {18: [stock.move(26,), stock.move(30,)], 19: [stock.move(27,)]}
        for dest_location_id in dest_location_ids:
            _logger.info(dest_location_id)
            location_id = 0
            location_dest_id = 0
            if(in_out == 'incoming'):
                location_id = self.location_dest_id.id
                location_dest_id = dest_location_id
            elif (in_out == 'outgoing'):
                location_id = dest_location_id
                location_dest_id = self.location_id.id
            picking = self.env['stock.picking'].create({
                'picking_type_id': picking_type_id.id,
                'location_id': location_id,  # 源地址
                'location_dest_id': location_dest_id,  # 目的地址
                'partner_id': self.partner_id.id,
                'owner_id': self.owner_id.id,
                'origin': self.name,
                'state': 'draft',
            })
            for move in dest_location_ids[dest_location_id]:
                product_uom_qty = 0
                if(in_out == 'incoming'):
                    product_uom_qty = move.quantity_done
                elif (in_out == 'outgoing'):
                    product_uom_qty = move.product_uom_qty
                picking.write({'move_ids_without_package': [(0, _, {
                    'name': 'eh move',
                    'product_id': move.product_id.id,
                    'product_uom_qty': product_uom_qty,
                    'product_uom': move.product_id.uom_id.id,
                    'location_id': move.location_dest_id.id,
                    'location_dest_id': move.eh_location_id.id,
                    'warehouse_id': move.warehouse_id.id,
                    'picking_type_id': picking_type_id.id,
                    'state': 'draft',
                })]})
            picking.action_confirm()
            self.write({'en_is_auto_generate_picking': True})

        # pickings = {}
        # for dest_location_id in dest_location_ids:
        #     picking = self.env['stock.picking'].create({
        #         'picking_type_id': picking_type_id.id,
        #         'location_id': self.location_dest_id.id,
        #         'location_dest_id': dest_location_id,
        #         'state': 'draft',
        #     })
        #     pickings[dest_location_id] = picking.id
        # return pickings

    # def _generate_move(self, picking_type_id, pickings):
    #     for move in self.move_lines:
    #         if pickings.has_key(move.eh_location_id.id):
    #             self.env['stock.move'].create({
    #                 'name': 'eh move',
    #                 'product_id': move.product_id.id,
    #                 'product_uom_qty': move.quantity_done,
    #                 'product_uom': move.product_id.uom_id.id,
    #                 'location_id': move.location_dest_id.id,
    #                 'location_dest_id': move.eh_location_id.id,
    #                 'warehouse_id': move.warehouse_id.id,
    #                 'picking_type_id': picking_type_id.id,
    #                 'state': 'draft',
    #             })
    #     return

    # def _put_move_picking(self, pickings, moves):
    #     return
